package validation

import (
	"errors"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
	"reflect"
)

func RegisterValidation() error {
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		return v.RegisterValidation("mobile", Mobile)
	} else {
		return errors.New("binding.Validator.Engine() Error")
	}
}

// ValidatorErrorMsg 表单验证定义错误
func ValidatorErrorMsg(err error, obj interface{}) string {
	paraObj := reflect.TypeOf(obj)
	var errs validator.ValidationErrors
	if errors.As(err, &errs) {
		for _, e := range errs {
			if f, exist := paraObj.Elem().FieldByName(e.Field()); exist {
				return f.Tag.Get("msg")
			}
		}
	}
	return err.Error()
}
